'''
Created on 2012-8-6

'''
import httplib
import json

class GCMWrapper:
    """
    A wrapper class helps to send google cloud messaging.
    Refer to: http://developer.android.com/guide/google/gcm/gcm.html#send-msg
    """
    
    api_key = "";
    gcm_url = "android.googleapis.com";
    
    def __init__(self, api_key):
        self.api_key = api_key;
        
    def notify(self, device_registration_ids, json_format_message):
        """
        Send notification message to devices.
        param: device_registration_ids should be a list of device registeration ids,
               For examle: ["xxx", "yyy", "zzz"]
        param: json_format_message should be dict type message,
               For example: {"type": 1, "message": "hello, world!"}
        """
            
        body = json.dumps({"registration_ids": device_registration_ids ,
                           "collapse_key": "GCM",
                           "data": json_format_message
                           });
        headers = {"Content-type": "application/json",
                   "Authorization": "key=" + self.api_key}
 
        conn = httplib.HTTPSConnection(host=self.gcm_url, port=443)
        conn.set_debuglevel(1)
        conn.request("POST", "/gcm/send", body, headers)
        response = conn.getresponse()
        
        print response.status, response.reason
        if response.status == 200:
            response_data = response.read()
            print(response_data)
  
        conn.close()
        
        return { "status": response.status, "response": response_data };
